import { View } from "@tarojs/components";
import { useEffect, useRef, useState } from "react";
import { ArrowDown } from "@taroify/icons";
import {
  Form,
  Input,
  Cell,
  Textarea,
  Picker,
  Popup,
  Uploader,
  Button,
  Toast,
} from "@taroify/core";
import Taro from "@tarojs/taro";
import Bg from "@/assets/images/bg.jpg";
import { requestPOST } from "@/request";

interface FormType {
  productName: string;
  productDescription: string;
  purchaseQuantity: string;
  purchaseUnit: string;
  purchaseName: string;
  purchaseImage: string;
}

export default function Quotation() {
  const [columns, setColumns] = useState<any[]>([]);
  const [openPicker, setOpenPicker] = useState(false);
  const [files, setFiles] = useState<Uploader.File[]>([]);
  const [loading, setLoading] = useState(false);

  const [form, setForm] = useState<FormType>({
    productName: "",
    productDescription: "",
    purchaseQuantity: "",
    purchaseUnit: "",
    purchaseName: "",
    purchaseImage: "",
  });

  const confirmQuantity = (values) => {
    const value = values[0];

    setForm({
      ...form,
      purchaseUnit: value,
      purchaseName: columns.find((item) => item.value === value)?.label!,
    });
  };

  const onUpload = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
    }).then(({ tempFiles, tempFilePaths }) => {
      Taro.uploadFile({
        url: process.env.TARO_APP_API + "/other/upload",
        filePath: tempFilePaths[0],
        name: "file",
        success(res) {
          setFiles([
            ...tempFiles.map(({ path, type, originalFileObj }) => ({
              type,
              url: path,
              name: originalFileObj?.name,
            })),
          ]);
          const { relativeUrl } = JSON.parse(res.data).data;
          setForm({
            ...form,
            purchaseImage: relativeUrl,
          });
          Toast.open({ type: "success", message: "upload success" });
        },
        fail() {
          Toast.open({ type: "fail", message: "upload error" });
        },
      });
    });
  };

  const onSubmit = () => {
    setLoading(true);
    requestPOST("other/sendProcurement", { ...form })
      .then(() => {
        Toast.open({ type: "success", message: "submit success" });
        setFiles([]);
        setForm({
          ...form,
          productName: "",
          productDescription: "",
          purchaseQuantity: "",
          purchaseImage: "",
        });
        formRef.current?.reset();
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const getColumnList = () => {
    requestPOST("other/getDictLabel/purchase_unit").then((res: any) => {
      setColumns(
        res.map((item) => ({ label: item.dictLabel, value: item.dictValue }))
      );
      setForm({
        ...form,
        purchaseUnit: res[0].dictValue,
        purchaseName: res[0].dictLabel,
      });
    });
  };

  useEffect(() => {
    getColumnList();
  }, []);

  const formRef = useRef<any>();

  return (
    <View>
      <View>
        {/* <View style={{ padding: "16px" }}>Want to get quotations？</View> */}
        <View
          style={{
            background: `url(${Bg}) `,
            padding: "16px 0",
            marginTop: "16px",
          }}
        >
          <Form ref={formRef} onSubmit={onSubmit}>
            <Cell.Group inset>
              <Form.Item
                name="productName"
                rules={[
                  { required: true, message: "please input productName" },
                ]}
              >
                <Form.Label>name</Form.Label>
                <Form.Control>
                  <Input
                    value={form.productName}
                    onChange={(e) =>
                      setForm({ ...form, productName: e.detail.value })
                    }
                    placeholder="Product Name or Keywords"
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item
                name="productDescription"
                rules={[
                  {
                    required: true,
                    message: "please input productDescription",
                  },
                ]}
              >
                <Form.Label>description</Form.Label>
                <Form.Control>
                  <Textarea
                    value={form.productDescription}
                    onChange={(e) =>
                      setForm({ ...form, productDescription: e.detail.value })
                    }
                    style={{ height: "80px" }}
                    limit={255}
                    placeholder="Product Description"
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item
                name="purchaseQuantity"
                rules={[
                  { required: true, message: "please input purchaseQuantity" },
                ]}
              >
                <Form.Label>quantity</Form.Label>
                <Form.Control>
                  <Input
                    value={form.purchaseQuantity}
                    onChange={(e) =>
                      setForm({ ...form, purchaseQuantity: e.detail.value })
                    }
                    type="number"
                    placeholder="Purchase Quantity"
                  />
                  <View
                    onClick={() => setOpenPicker(true)}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: "5px",
                    }}
                  >
                    {form.purchaseName}
                    <ArrowDown />
                  </View>
                </Form.Control>
              </Form.Item>
              <Form.Item name="purchaseImage">
                <Form.Control>
                  <Uploader
                    value={files}
                    onUpload={onUpload}
                    onChange={setFiles}
                  />
                </Form.Control>
              </Form.Item>
            </Cell.Group>
            <View style={{ margin: "16px" }}>
              <Button loading={loading} block color="primary" formType="submit">
                Post Your Request Now
              </Button>
            </View>
          </Form>
        </View>
      </View>

      <Popup
        open={openPicker}
        rounded
        placement="bottom"
        onClose={() => setOpenPicker(false)}
      >
        <Picker
          title="Purchase Quantity"
          columns={columns}
          onCancel={() => setOpenPicker(false)}
          onConfirm={(values) => confirmQuantity(values)}
        ></Picker>
      </Popup>
    </View>
  );
}
